package com.winit.common.filter;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.winit.common.base.beans.LoginUser;
import com.winit.common.util.Constants;
import com.winit.common.util.JSONFileUtil;
import com.winit.common.base.beans.RoleInfo;
import com.winit.common.util.ObjectToString;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;


public class SessionValidFilter implements Filter {

    private Logger log = LoggerFactory.getLogger(SessionValidFilter.class);

    public void destroy() {

    }

    public void doFilter(ServletRequest req, ServletResponse res,
                         FilterChain chain) throws IOException, ServletException {
        // 做权限控制
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request = (HttpServletRequest) req;
        String url = request.getRequestURI();// 用户请求地址

        //过滤ws请求
        if (!StringUtils.isEmpty(request.getHeader("Upgrade"))
                && "websocket".equals(request.getHeader("Upgrade"))) {
            chain.doFilter(req, res);
            return;
        }

        if (!StringUtils.isEmpty(url)
                && ("/beetle/mq/websocket".equals(url)
                || "/beetle/vmJobLogMQ/websocket".equals(url))) {
            chain.doFilter(req, res);
            return;
        }

        ((HttpServletResponse) res).setHeader("Access-Control-Allow-Origin", "*");
        ((HttpServletResponse) res).setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS");
        ((HttpServletResponse) res).setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

        if (!StringUtils.isEmpty(url)
                && ("/beetle/user/login".equals(url)
                || "/beetle/error/noUser".equals(url)
                || "/beetle/error/noPower".equals(url)
                || "/beetle/project/getTrunkNameList".equals(url)
                || "/beetle/uCloud/getProjectReleaseVersions".equals(url)
                || "/beetle/uCloud/ogg/clean".equals(url)
                || "/beetle/uCloud/ogg/do".equals(url)
                || "/beetle/uCloud/getProjectVersions".equals(url))) {
            chain.doFilter(req, res);
            return;
        }
//		获取用户登录信息
        LoginUser userInfo = UserInfoUtil.getUserInfo(request);
        log.info("com.winit.common.filter.SessionValidFilter.doFilter url=" + url + ",userInfo=" + ObjectToString.getString(userInfo));
        if (userInfo != null) {
//			判断用户角色是否有该url的访问权限
            if (!checkRole(url, userInfo.getUserRole())) {
                log.info("调用接口,用户没有访问权限,url=" + url + ",userName=" + userInfo.getUserName() + ",userRole=" + userInfo.getUserRole());
                redirect(response, "/beetle/error/noPower");
                return;
            }
            chain.doFilter(req, res);
            return;
        } else {
            log.info("调用接口,获取用户信息为空,url=" + url);
            redirect(response, "/beetle/error/noUser");
            return;
        }
    }

    private boolean checkRole(String url, List<RoleInfo> roleList) {

//		管理员可访问任何权限
        if (roleList.contains(Constants.USER_ROLE_ADMIN)) {
            return true;
        }

        Map<String, List<String>> roleCheckUrl = JSONFileUtil.getFileJsonForBean(Thread.currentThread().getContextClassLoader().getResource("").getPath()
                + "data/url_power.json", Map.class);

        //判断url是否需要权限控制 没有配置的url所有角色都可访问
        if (!roleCheckUrl.containsKey(url)) {
            return true;
        }

//		判断角色访问权限 存在角色说明可以访问
        List<String> roles = roleCheckUrl.get(url);

        for (RoleInfo roleInfo : roleList) {
            if (roles.contains(roleInfo.getRole_name())) {
                return true;
            }
        }
        return false;
    }

    private void redirect(HttpServletResponse response, String url)
            throws IOException {
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Cache-Control", "no-store");
        response.setDateHeader("Expires", 0);

        response.sendRedirect(url);
    }

    public void init(FilterConfig config) throws ServletException {
    }
}
